﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace PDX.Validation
{
    /// <summary>
    /// Looks for validation failures of any System.ComponentModel.DataAnnotations
    /// defined on the <see cref="IPropertyResolution"/>.
    /// </summary>
    public class DataAnnotationsAdapter : IValidationAdapter
    {
        /// <summary>
        /// Gets a validation failure message.
        /// Return null or String.Empty to indicate there is no error.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public string GetMessage(Context context)
        {
            var resolution = context.GetResolution();
            var propertyModel = context.GetPropertyModel();

            if (resolution == null || resolution.Property == null || propertyModel == null)
            {
                return string.Empty;
            }

            var displayName = propertyModel.DisplayName;
            if (string.IsNullOrEmpty(displayName))
            {
                displayName = resolution.Property.Name;
            }

            foreach (var att in resolution.Property.GetCustomAttributes(true).OfType<ValidationAttribute>())
            {
                if (!att.IsValid(propertyModel.Value))
                {
                    return att.FormatErrorMessage(String.Format("'{0}'", displayName));
                }
            }

            return string.Empty;
        }
    }
}
